﻿using Dao;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using HospitalErpWinUI.GlobalVar;
using HospitalErpWinUI.WinFormUiHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Windows.Forms;

namespace HospitalErpWinUI.hbos.acct.acctbook.balance.subjitem
{ 
    public partial class main : RibbonForm
    {
        protected DaoHelper _helper;
        DataTable _user = new DataTable();

        //初始化绑定默认关键词（此数据源可以从数据库取） 
        List<string> _groupsInit = new List<string>();
        List<string> _groupsChange = new List<string>();
        List<String> _itemsList = new List<String>();
        List<String> _itemCodeList = new List<String>();
        List<String> _itemCodeList2 = new List<String>();
        string[] codeArray2 = new String[]{};
        string[] valueArray2 = new String[]{};
        public main()
        {
            _helper = new DaoHelper();
            InitializeComponent();
        }

        
        private void getAcctSubj1()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_subj_specialNameForCheck";
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code); 
            paramters.Add("acct_year", G_User.user.Acct_year);
            paramters.Add("key", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit1).Trim());

            serviceParamter.Paramters = paramters;

            List<CodeValue> objs = new List<CodeValue>();
            DataTable dt = _helper.ReadDictForSql(serviceParamter);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CodeValue codeValue = new CodeValue();
                codeValue.Code = dt.Rows[i][0].ToString();
                codeValue.Value = dt.Rows[i][1].ToString();
                objs.Add(codeValue);
            }
            searchLookUpEdit1.Properties.ValueMember = "Code";
            searchLookUpEdit1.Properties.DisplayMember = "Value";
            searchLookUpEdit1.Properties.DataSource = objs;
        }


        //获取核算项数据
        private void getItemList()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_subj_checkItemClass_subj";
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            paramters.Add("acct_year", G_User.user.Acct_year);
            paramters.Add("acct_subj_code", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit1).Trim());
            serviceParamter.Paramters = paramters;
            DataTable groups = _helper.ReadDictForSql(serviceParamter);
            checkedComboBoxEdit1.Properties.Items.Clear();

            CheckedListBoxItem[] itemListQuery = new CheckedListBoxItem[groups.Rows.Count + 1];
            int check = 1;
            for (int i = 0; i < groups.Rows.Count; i++)
            {
                itemListQuery[check] = new CheckedListBoxItem(groups.Rows[i][0].ToString(), groups.Rows[i][1].ToString());
                check++;

            }

            checkedComboBoxEdit1.Properties.Items.AddRange(itemListQuery);



        }

        //动态创建辅助核算下拉框
        private void createItemList(String itemNames)
        {
            string[] itemNameArry = itemNames.Split(',');
            int i = 30;
            int g = 60;
            int j = 1;
            int k = 0;

            //删除动态控件
            deleteItem(_itemsList, i,g);



            foreach (string s in itemNameArry)
            {

                if (s.Equals(""))
                {
                    return;
                }
                //通过code获取value

             
                LabelControl labelControl = new LabelControl();
                SearchLookUpEdit searchLookUpEdit = new SearchLookUpEdit();
              
                labelControl.Name = "labelControl" + i;
                labelControl.Location = new System.Drawing.Point(30* j, 50);
                labelControl.TabIndex = i + 1;
                labelControl.Text = s + ":";


                searchLookUpEdit.Name = "searchLookUpEdit" + i;
                searchLookUpEdit.Location = new System.Drawing.Point(labelControl.Location.X+40, 45);
                searchLookUpEdit.TabIndex = i + 1;
                searchLookUpEdit.Properties.NullText = "";
                searchLookUpEdit.Properties.ShowFooter = false;
                searchLookUpEdit.Properties.ShowClearButton = false;
                searchLookUpEdit.EditValueChanged += new System.EventHandler(searchLookUpEdit_EditValueChange);
                //searchLookUpEdit.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(searchLookUpEdit_ButtonClick);
                // searchLookUpEdit.EditValue = "000000";
                LabelControl labelControl2 = new LabelControl();
                SearchLookUpEdit searchLookUpEdit2 = new SearchLookUpEdit();
                labelControl2.Name = "labelControl" + g;
                labelControl2.Location = new System.Drawing.Point(searchLookUpEdit.Location.X+searchLookUpEdit.Size.Width, 50);
                labelControl2.TabIndex = g + 1;
                labelControl2.Text = "到";
                searchLookUpEdit2.Name = "searchLookUpEdit" + g;
                searchLookUpEdit2.Location = new System.Drawing.Point( labelControl2.Location.X+15, 45);
                searchLookUpEdit2.TabIndex = g + 1;
                searchLookUpEdit2.Properties.NullText = "";
                searchLookUpEdit2.Properties.ShowFooter = false;
                searchLookUpEdit2.Properties.ShowClearButton = false;
                searchLookUpEdit2.EditValueChanged += new System.EventHandler(searchLookUpEdit2_EditValueChange);
                panelControl2.Controls.Add(labelControl);
                panelControl2.Controls.Add(searchLookUpEdit);
                panelControl2.Controls.Add(labelControl2);
                panelControl2.Controls.Add(searchLookUpEdit2);

     
                String cid = getCid(searchLookUpEdit,k);
        
                getSelectItemList(cid, searchLookUpEdit);
                getSelectItemList(cid, searchLookUpEdit2);

                k++;
                i++;
                g++;
                j = j + 10;

            }

            _itemsList.Clear();

            foreach (string s in itemNameArry)
            {
                _itemsList.Add(s);
            }

        }

        //得到辅助核算的cid
        private String getCid(SearchLookUpEdit searchLookUpEdit,int k) 
        {
            String para = "<root><tbody><tr><pk>" + codeArray2[k].Trim() + "</pk><td1>" + codeArray2[k].Trim() + "</td1><td2></td2><td3></td3><td4></td4></tr></tbody></root>";
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_subj_ActiveClassBetweenConditionFast1";
            paramters.Add("acct_year", G_User.user.Acct_year); 
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            paramters.Add("subjCheckItems", para);
            paramters.Add("subjcodeB", "");
            paramters.Add("subjcodeE", "");
            paramters.Add("Curcode", "");
            paramters.Add("acct_monthB", "2019-01-01");//dateEdit1.DateTime.ToString("yyyy-MM-dd"));
            paramters.Add("acct_monthE", "2019-05-31");//dateEdit2.DateTime.ToString("yyyy-MM-dd"));
            paramters.Add("cb1", FormHelper.GetValueForCheckEdit(checkEdit3).Trim());
            paramters.Add("cb2", FormHelper.GetValueForCheckEdit(checkEdit4).Trim());
            paramters.Add("fieldname", codeArray2[k].Trim());
            paramters.Add("fieldname_ch", valueArray2[k].Trim());
            paramters.Add("key", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit).Trim());
       

            serviceParamter.Paramters = paramters;

            List<CodeValue> objs = new List<CodeValue>();
            DataTable dt = _helper.ReadDictForSql(serviceParamter);
            /*for (int i = 0; i < dt.Rows.Count; i++)
            {
                CodeValue codeValue = new CodeValue();
                codeValue.Code = dt.Rows[i][0].ToString();
                codeValue.Value = dt.Rows[i][1].ToString();
                objs.Add(codeValue);
            }
            searchLookUpEdit1.Properties.ValueMember = "Code";
            searchLookUpEdit1.Properties.DisplayMember = "Value";
            searchLookUpEdit1.Properties.DataSource = objs;*/
            return dt.Rows[0][0].ToString();
        
        }

        //删除控件
        private void deleteItem(List<String> _itemsList, int i,int g)
        {
            for (int j = i; j <= _itemsList.Count() + i; j++)
            {
                panelControl2.Controls.RemoveByKey("searchLookUpEdit" + j);

                panelControl2.Controls.RemoveByKey("labelControl" + j);

            }

            for (int j = g; j <= _itemsList.Count() + g; j++)
            {
                panelControl2.Controls.RemoveByKey("searchLookUpEdit" + j);

                panelControl2.Controls.RemoveByKey("labelControl" + j);

            }

        }


        //获取每个核算项数据
        private void getSelectItemList(String cid, SearchLookUpEdit searchLookUpEdit)
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_subj_ActiveClassBetweenConditionFastS";
            paramters.Add("table_name", cid);
            paramters.Add("key", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit).Trim());
            // paramters.Add("acct_year", G_User.user.Acct_year);
            serviceParamter.Paramters = paramters;

            List<CodeValue> objs = new List<CodeValue>();
            DataTable dt = _helper.ReadDictForSql(serviceParamter);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CodeValue codeValue = new CodeValue();
                codeValue.Code = dt.Rows[i][0].ToString();
                codeValue.Value = dt.Rows[i][1].ToString();
                objs.Add(codeValue);
            }
            //    emp_code.Properties.Items.AddRange(emps);
            searchLookUpEdit.Properties.ValueMember = "Code";
            searchLookUpEdit.Properties.DisplayMember = "Value";
            searchLookUpEdit.Properties.DataSource = objs;

        }

        private void init()
        {
            
            //科目字段数据赋值
            getAcctSubj1();
            //设置默认日期
            dateEdit1.Text = DateTime.Now.ToString("yyyy-MM-01");//本月第一天
            dateEdit2.Text = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");//本月最后一天

            //获取辅助核算
            getItemList();

        }


        private void main_Load(object sender, EventArgs e)
        {
            init();
        }

        private void checkedComboBoxEdit1_TextChanged(object sender, EventArgs e)
        {
            codeArray2 = checkedComboBoxEdit1.EditValue.ToString().Trim().Split(',');
            valueArray2 = checkedComboBoxEdit1.Text.ToString().Trim().Split(',');
            createItemList(checkedComboBoxEdit1.Text.ToString().Trim());
            _itemCodeList.RemoveRange(0,_itemCodeList.Count);
            _itemCodeList2.RemoveRange(0,_itemCodeList2.Count);

        }

        private void searchLookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {
            getItemList();
        }

        private void searchLookUpEdit_EditValueChange(object sender, EventArgs e)
        {
            SearchLookUpEdit searchLookUpEdit = sender as SearchLookUpEdit;
          
            if (searchLookUpEdit.EditValue.ToString().Trim() != "" || searchLookUpEdit.EditValue.ToString().Trim() != null)
            {
                if (_itemCodeList.Count < valueArray2.Length*2)
                {
                    _itemCodeList.Add(searchLookUpEdit.TabIndex.ToString());
                    _itemCodeList.Add(searchLookUpEdit.EditValue.ToString().Trim());
                }
                else 
                {
                    _itemCodeList[getIndexCheckedComboBoxEdit(searchLookUpEdit.TabIndex.ToString(), _itemCodeList)] = searchLookUpEdit.EditValue.ToString().Trim();
                }
                
            }


        }

      
        private void searchLookUpEdit2_EditValueChange(object sender, EventArgs e)
        {
            SearchLookUpEdit searchLookUpEdit2 = sender as SearchLookUpEdit;

            if (searchLookUpEdit2.EditValue.ToString().Trim() != "" || searchLookUpEdit2.EditValue.ToString().Trim() != null)
            {
                if (_itemCodeList2.Count < valueArray2.Length*2)
                {
                    _itemCodeList2.Add(searchLookUpEdit2.TabIndex.ToString());
                    _itemCodeList2.Add(searchLookUpEdit2.EditValue.ToString().Trim());
                }
                else
                {
                    _itemCodeList2[getIndexCheckedComboBoxEdit(searchLookUpEdit2.TabIndex.ToString(), _itemCodeList2)] = searchLookUpEdit2.EditValue.ToString().Trim();
                }
            }
        }

        private int getIndexCheckedComboBoxEdit(String tabIndex, List<String> _itemCodeList)
        {
           // MessageBox.Show(tabIndex);
            int i = 0;
            int j = 0;
            foreach (String item in _itemCodeList)
            {
                if (item.Equals(tabIndex))
                {
                    j = i;
                }
                i++;
            }
            return j + 1;
        }
        //封装动态辅助核算参数
        //checkedComboBoxEdit1.EditValue.ToString().Trim()、checkedComboBoxEdit1.Text.ToString().Trim()
        private String getItemParas()
        {
            string[] codeArray = checkedComboBoxEdit1.EditValue.ToString().Trim().Split(','); //checkedComboBoxEdit1.EditValue.ToString().Trim().Split(",");
            string[] valueArray = checkedComboBoxEdit1.Text.ToString().Trim().Split(',');

            int i = 0;
            int j = 0;
            int e = 1;
            int k = _itemCodeList.Count/codeArray.Length;
            int f = _itemCodeList2.Count/codeArray.Length;
            int g = _itemsList.Count;
 
           // MessageBox.Show(String.Join(",", _itemCodeList));
            //MessageBox.Show(String.Join(",", _itemCodeList2));
   


            String para = "";
            foreach (String code in codeArray)
            {
                if (j < k)
                {
                    para = para + "<tr><pk>" + code.Trim() + "</pk><td1>" + valueArray[i].Trim() + "</td1><value></value><td2>" + _itemCodeList[2 * e - 1] + "</td2><td3>" + _itemCodeList2[2 * e - 1] + "</td3></tr>"; 
                }
                /*else
                {
                    para = para + "<tr><pk>" + code.Trim() + "</pk><td1>" + valueArray[i].Trim() + "</td1><value></value><td2>" + _itemCodeList[j] + "+</td2><td3>" + _itemCodeList2[j] + "</td3></tr>";
                }*/
                i++;
                j++;
                e++;
            }
            para = "<root><tbody>" + para + "</tbody></root>";
            return para;
        }

        #region 创建动态表

        // 创建bandedGridColumn列的方法 
        private void CreateGridColumn()
        {
            BandedGridView view = this.bandedGridView1;
            view.BeginUpdate(); //开始视图的编辑，防止触发其他事件
            view.BeginDataUpdate(); //开始数据的编辑
            view.Bands.Clear();
            view.Columns.Clear();


            //gridBand1.Columns.Clear();
 
            for (int i = 0; i < valueArray2.Length; i++)
            {
                GridBand band1 = view.Bands.AddBand(valueArray2[i]);

                var bandedGridColumn = new BandedGridColumn();
                bandedGridColumn.Caption = valueArray2[i];
                bandedGridColumn.FieldName = codeArray2[i];
                bandedGridColumn.Visible = true;
                bandedGridColumn.VisibleIndex = i;
                band1.Columns.Add(bandedGridColumn);
                band1.MinWidth = 150;
                if (i+1 == valueArray2.Length)
                {
                    if (FormHelper.GetValueForCheckEdit(checkEdit1).Trim() =="1") 
                    {
                        GridBand band2 = view.Bands.AddBand("年初余额");
                        GridBand band2J = band2.Children.AddBand("借方");
                        GridBand band2D = band2.Children.AddBand("贷方");

                        band2J.Columns.Add(createStaticColumn("借方", "startyear_J", true, i + 1, true));
                        band2D.Columns.Add(createStaticColumn("贷方", "startyear_D", true, i + 2, true));
                     
                    }
                    GridBand band3 = view.Bands.AddBand("期初余额");
                    GridBand band3J = band3.Children.AddBand("借方");
                    GridBand band3D = band3.Children.AddBand("贷方");
                    band3J.Columns.Add(createStaticColumn("借方", "start_J", true, i + 3, true));
                    band3D.Columns.Add(createStaticColumn("贷方", "start_D", true, i + 4, true));


                    GridBand band4 = view.Bands.AddBand("本期发生额");
                    GridBand band4J = band4.Children.AddBand("借方");
                    GridBand band4D = band4.Children.AddBand("贷方");
                    band4J.Columns.Add(createStaticColumn("借方", "cur_J", true, i + 5, true));
                    band4D.Columns.Add(createStaticColumn("贷方", "cur_D", true, i + 6, true));
                    
                   
                    
                    
                    if (FormHelper.GetValueForCheckEdit(checkEdit2).Trim() == "1")
                    {
                        GridBand band5 = view.Bands.AddBand("本年累计");
                        GridBand band5J = band5.Children.AddBand("借方");
                        GridBand band5D = band5.Children.AddBand("贷方");
                        band5J.Columns.Add(createStaticColumn("借方", "theyear_J", true, i + 7, true));
                        band5D.Columns.Add(createStaticColumn("贷方", "theyear_D", true, i + 8, true));
                    }
                    GridBand band6 = view.Bands.AddBand("期末余额");
                    GridBand band6J = band6.Children.AddBand("借方");
                    GridBand band6D = band6.Children.AddBand("贷方");
                    band6J.Columns.Add(createStaticColumn("借方", "end_J", true, i + 9, true));
                    band6D.Columns.Add(createStaticColumn("贷方", "end_D", true, i + 10, true));

                    GridBand band7 = view.Bands.AddBand("是否包含年初");
                    band7.Columns.Add(createStaticColumn("是否包含年初", "isclude", true, i + 11, true));
                    band7.Visible = false;

                    GridBand band8 = view.Bands.AddBand("是否包含本年");
                    band8.Columns.Add(createStaticColumn("是否包含本年", "iscludestart", true, i + 12, true));
                    band8.Visible = false;
                    GridBand band9 = view.Bands.AddBand("PK");
                    band9.Columns.Add(createStaticColumn("PK", "_PK", true, i + 13, true));
                    band9.Visible = false;
                
                }
            }


            ///循环对齐表头
            for (int i = 0; i < this.bandedGridView1.Columns.Count; i++)
            {
                this.bandedGridView1.Columns[i].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;//表头居中对齐
            }

            ///循环对齐BandedGridView控件的GridBand控件 表头
            for (int i = 0; i < this.bandedGridView1.Bands.Count; i++)
            {
                this.bandedGridView1.Bands[i].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;//居中对齐
            }

            view.EndDataUpdate();//结束数据的编辑
            view.EndUpdate();   //结束视图的编辑
            view.OptionsView.ShowGroupPanel=false;
            view.OptionsView.ShowColumnHeaders = false;


        }

        private BandedGridColumn createStaticColumn(String caption, String FieldName, Boolean visible, int visibleIndex, Boolean colVisible) 
        {
            var bandedGridColumn = new BandedGridColumn();
            bandedGridColumn.Caption = caption;
            bandedGridColumn.FieldName = FieldName;
            bandedGridColumn.Visible = visible;
            bandedGridColumn.VisibleIndex = visibleIndex;

            return bandedGridColumn;
        }


        #endregion

        #region 主查询
        private void Query()
        {
            CreateGridColumn();
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "acct_acctbook_balance_subj_item";
            paramters.Add("acct_year", G_User.user.Acct_year);
            paramters.Add("comp_code", G_User.user.Comp_code);
            paramters.Add("copy_code", G_User.user.Copy_code);
            paramters.Add("subjCheckItems", getItemParas());
            paramters.Add("curr_code", "RMB");
            paramters.Add("start_time", "2019-01-01");
            paramters.Add("end_time", "2019-05-31");
            paramters.Add("start_subj", FormHelper.GetValueForSearchLookUpEdit(searchLookUpEdit1).Trim());
            paramters.Add("isclude", FormHelper.GetValueForCheckEdit(checkEdit2).Trim());
            paramters.Add("iscludestart", FormHelper.GetValueForCheckEdit(checkEdit1).Trim());
            paramters.Add("cb1", FormHelper.GetValueForCheckEdit(checkEdit3).Trim());
            paramters.Add("cb2", FormHelper.GetValueForCheckEdit(checkEdit4).Trim());
            
            serviceParamter.Paramters = paramters;

            DataTable dt = _helper.ReadSqlForDataTable(serviceParamter);
            dt.Columns.Add("checked", System.Type.GetType("System.Boolean"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["checked"] = "false";
            }
            _user = dt;
            gridControl1.DataSource = _user;

        }
        #endregion

        private void acct_acctbook_balance_item_subj_Click(object sender, EventArgs e)
        {
            try
            {
                Query();
            }
            catch (Exception ex)
            {
                MessageForm.Exception(ex.Message);
            }
        }



       
        
    }
}
